import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/login/login_password_page.dart';
import 'package:flutter_syt/domain/login/widgets/login_input_decorator.dart';
import 'package:flutter_syt/domain/login/widgets/login_phone_form_field.dart';
import 'package:flutter_syt/domain/login/widgets/login_protocol.dart';
import 'package:flutter_syt/domain/widgets/code_form_field.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_comment.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/common_button.dart';

class RegisterPhonePage extends StatefulWidget {
  @override
  RegisterPhonePageState createState() => RegisterPhonePageState();
}

class RegisterPhonePageState extends State<RegisterPhonePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  final _formPhoneKey = GlobalKey<FormState>();

  FocusNode phoneFocusNode = FocusNode();
  FocusNode pwdFocusNode = FocusNode();
  FocusNode codeFocusNode = FocusNode();

  String _code = '',
      _password = '',
      _codeEmail = '',
      _passwordEmail = '',
      _email = '';

  bool _agree = false;

  bool blurBackground = false;

  bool pwsPhoneobscureText = true;
  late PhoneWithAreaCodeEntity _phone;

  @override
  Widget build(BuildContext context) {
    DLog('casdcasdvadsv');
    super.build(context);
    return Form(
        key: _formPhoneKey,
        child: Container(
            padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 30),
            // height: 300.w,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                LoginPhoneFormField(
                  focusNode: phoneFocusNode,
                  onSaved: (val) => _phone = val!,
                ),

                const SizedBox(
                  height: 24,
                ),

                CodeFormField(
                  tagStr: 'registerphone',
                  focusNode: codeFocusNode,
                  getSmsCode: getSmsCode,
                  decoration: LoginInputDecoration(),
                  onSaved: (val) => _code = val!,
                ),

                // LoginCodeFormField(
                //   mobileController: mobileController,
                //   onSaved: (val) => _code = val!,
                // ),
                const SizedBox(
                  height: 24,
                ),
                // BlurRectWidget(
                TextFormField(
                  enableInteractiveSelection: false,
                  maxLength: 16,
                  inputFormatters: [
                    FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                  ],
                  autofocus: false,
                  focusNode: pwdFocusNode,
                  style: const TextStyle(
                    color: Colors.black,
                    fontSize: 14,
                  ),
                  cursorColor: ThemeColor.primaryColor,
                  decoration: LoginInputDecoration(
                    hintText: S.of(context).Password_8_16,
                    suffixIcon: GestureDetector(
                      onTap: ClickUtils.debounce(() {
                        if (mounted) {
                          setState(() {
                            pwsPhoneobscureText = !pwsPhoneobscureText;
                          });
                        }
                      }),
                      child: Container(
                          width: 20,
                          child: Center(
                            child: Image.asset(
                              pwsPhoneobscureText
                                  ? 'assets/images/comment_obscureText_open.png'
                                  : 'assets/images/comment_obscureText_close.png',
                              width: 20,
                              color: Colors.white,
                              height: pwsPhoneobscureText ? 20 : 14,
                            ),
                          )),
                    ),
                  ),
                  validator: (val) {
                    if (val != null) {
                      if (!UtilsComment.checkPasswordFormal(val)) {
                        customShowToast(S.of(context).passwordToast_8_16);
                        return '';
                      }
                    }
                    return null;
                  },
                  onSaved: (val) => _password = val!,
                  obscureText: pwsPhoneobscureText,
                  // keyboardType: TextInputType.text,
                  keyboardType: TextInputType.visiblePassword,
                  autocorrect: false,
                ),

                SizedBox(
                  height: 30,
                ),
                LoginProtocol(onChange: (value) {
                  setState(() {
                    _agree = value;
                  });
                }),
                Container(
                  margin: const EdgeInsets.only(top: 30),
                  width: double.infinity,
                  // child: ElevatedButton(
                  //     child: Text(
                  //       S.of(context).sign_up2,
                  //       style: TextStyle(fontWeight: FontWeight.bold),
                  //     ),
                  //     onPressed: ClickUtils.debounce(
                  //       () async {
                  //         await _submit();
                  //       },
                  //     )),
                  child: CommonButton.expend(
                    title: S().sign_up2,
                    onAsyncClick: () async {
                      await _submit();
                    },
                  ),
                ),
              ],
              // ),
              // ),
            )));
  }

  Future _register() async {
    // DeviceInfoPlugin().deviceInfo;
    await API.shared.login.phoneRegister(
        _phone.areaCode, _phone.phone, _password, _code,
        device: (Platform.isIOS
            ? appContext.iOSInfo.identifierForVendor
            : appContext.andriodInfo.androidId));
  }

  Future _submit() async {
    final form = _formPhoneKey.currentState;
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return;
    }
    if (form!.validate()) {
      form.save();
      if (_code == '86') {
        if (!RegexUtil.isMobileSimple(_phone.phone)) {
          customShowToast(S.of(context).enter_valid_phone);
          return;
        }
      } else if (!RegexUtil.matches('^\\d{6,25}\$', _phone.phone)) {
        customShowToast(S.of(context).enter_valid_phone);
        return;
      }

      // Navigator.of(context).popUntil((route) => route.isFirst);
      try {
        await loading(_register, text: S.of(context).on_register);
        GlobalData.bindPush();
        GlobalData.getIndexSetting();
        if (GlobalData.pageFrom.isEmpty) {
          Navigator.of(context).pop();
          Navigator.of(context).pop();
        } else {
          Navigator.of(context).popUntil((route) {
            var name = route.settings.name;
            if (name != null) {
              return name.startsWith(GlobalData.pageFrom);
            }
            return route.isFirst;
          });
        }
        customShowSuccess(S.of(context).register_success);
      } catch (e) {
        UtilsOther.showCustomShowError(e);
      }
      // if (GlobalData.pageFrom.isEmpty) {
      //   Navigator.of(context).pop();
      // } else {
    }
  }

  Future<bool> getSmsCode() async {
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return false;
    }
    final form = _formPhoneKey.currentState;
    form!.save();
    if (_phone.areaCode == '86') {
      if (!RegexUtil.isMobileSimple(_phone.phone)) {
        customShowToast(S.of(context).enter_valid_phone);
        return false;
      }
    } else if (!RegexUtil.matches('^\\d{6,25}\$', _phone.phone)) {
      customShowToast(S.of(context).enter_valid_phone);
      return false;
    }
    // bool isVertifica = await UtilsOther.checkShowVertification(
    //     account: _phone.phone, type: '1', context: context);
    // if (isVertifica == false) {
    //   return false;
    // }

    try {
      bool res = await API.shared.login
          .getPhoneCode(_phone.areaCode, _phone.phone, 'register');
      customShowToast(S().send_code_2);
      return res;
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowError(e.message);
      // } else {
      //   customShowError(S().network_error);
      // }
      return true;
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    phoneFocusNode.dispose();
    codeFocusNode.dispose();
    pwdFocusNode.dispose();
  }

  @override
  void didUpdateWidget(RegisterPhonePage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
